package com.zhlq.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class ConfigTool {
	/** 配置项的key,value映射map */
	private static Map<String, String> map = new HashMap<String, String>();
	/** 默认的配置文件 */
	private static String name = "configuration.xml";

	static {
		// 加载默认的配置文件
		URL url = ConfigTool.class.getResource("/");
		File file = new File(url.getFile());
		String path = file.getParent() + "/config/" + name;
		load(path);
	}

	/**
	 * 加载指定的配置文件
	 * 
	 * @param fileName
	 */
	@SuppressWarnings("unchecked")
	public static void load(String path) {
		BufferedReader reader = null;
		List<Element> list = null;
		try{
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
			StringBuffer xml = new StringBuffer();
			String line = null;
			while ((line = reader.readLine()) != null) {
				xml.append(line);
			}
			Document doc = DocumentHelper.parseText(xml.toString());
			Element root = doc.getRootElement();
			list = root.elements();
		} catch (IOException | DocumentException e) {
			throw new RuntimeException(e);
		} finally {
			if(null != reader){
				try {
					reader.close();
				} catch (IOException e1) {
					throw new RuntimeException(e1);
				}
			}
		}
		// 保证在任何时候调用load方法时都能完重新加载配置
		map.clear();
		for (Element e : list) {
			String key = e.attributeValue("key");
			String attrValue = e.attributeValue("value");
			String txtValue = e.getText();
			// 优先使用不为null和长度大于0的，其次以attValue优先
			if (attrValue != null && attrValue.length() > 0) {
				map.put(key, attrValue);
			} else {
				map.put(key, txtValue);
			}
		}
	}

	/**
	 * 取得配置值
	 * 
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		return map.get(key);
	}
}
